<template>
  <div class="complaint-add">
    <el-page-header @back="goBack" :title="isView ? '查看投诉' : (isEdit ? '编辑投诉' : '添加投诉')"></el-page-header>
    
    <div class="form-container">
      <el-form 
        ref="complaintForm" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        :disabled="isView || loading"
      >
        <el-form-item label="投诉人" prop="ownerId">
          <el-select v-model="formData.ownerId" placeholder="请选择投诉人" style="width: 100%" @change="handleOwnerChange">
            <el-option v-for="owner in ownerOptions" :key="owner.id" :label="owner.name" :value="owner.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="ownerPhone">
          <el-input v-model="formData.ownerPhone" placeholder="业主电话" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="投诉标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入投诉标题"></el-input>
        </el-form-item>
        
        <el-form-item label="投诉类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择投诉类型" style="width: 100%">
            <el-option label="噪音投诉" value="噪音投诉"></el-option>
            <el-option label="环境卫生" value="环境卫生"></el-option>
            <el-option label="设施设备" value="设施设备"></el-option>
            <el-option label="车位纠纷" value="车位纠纷"></el-option>
            <el-option label="费用投诉" value="费用投诉"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="投诉内容" prop="content">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请详细描述投诉内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="投诉时间" prop="submitTime">
          <el-date-picker
            v-model="formData.submitTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理人员" prop="handlerName" v-if="formData.status !== '待处理'">
          <el-input v-model="formData.handlerName" placeholder="请输入处理人员姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="处理结果" prop="result" v-if="formData.status === '已完成'">
          <el-input 
            v-model="formData.result" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入处理结果描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-if="!isView" :loading="loading">保存</el-button>
          <el-button @click="goBack">{{ isView ? '返回' : '取消' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'ComplaintAdd',
  data() {
    return {
      isEdit: false,
      isView: false,
      formData: {
        id: null,
        ownerId: null,
        ownerName: '',
        ownerPhone: '',
        title: '',
        content: '',
        type: '',
        status: '待处理',
        submitTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        handleTime: null,
        finishTime: null,
        handlerName: '',
        result: ''
      },
      ownerOptions: [],
      loading: false,
      rules: {
        ownerId: [{ required: true, message: '请选择投诉人', trigger: 'change' }],
        title: [{ required: true, message: '请输入投诉标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择投诉类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入投诉内容', trigger: 'blur' }],
        status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
      }
    };
  },
  created() {
    // 加载业主选项
    this.fetchOwners();
    
    const id = this.$route.query.id;
    const view = this.$route.query.view;
    
    if (id) {
      this.isEdit = true;
      if (view === 'true') {
        this.isView = true;
      }
      this.fetchComplaintData(id);
    }
  },
  methods: {
    // 获取业主列表
    fetchOwners() {
      axios.get('/api/owners')
        .then(response => {
          if (Array.isArray(response.data)) {
            this.ownerOptions = response.data.map(owner => ({
              id: owner.id,
              name: owner.name,
              phone: owner.phoneNumber
            }));
          } else {
            this.ownerOptions = [];
          }
        })
        .catch(error => {
          console.error('获取业主列表失败:', error);
          ElMessage.error('获取业主列表失败');
        });
    },
    
    // 处理业主选择变更
    handleOwnerChange(ownerId) {
      const selectedOwner = this.ownerOptions.find(owner => owner.id === ownerId);
      if (selectedOwner) {
        this.formData.ownerName = selectedOwner.name;
        this.formData.ownerPhone = selectedOwner.phone;
      }
    },
    
    fetchComplaintData(id) {
      this.loading = true;
      axios.get(`/api/complaints/${id}`)
        .then(response => {
          const data = response.data;
          
          this.formData = {
            id: data.id,
            ownerId: data.ownerId,
            ownerName: data.ownerName,
            ownerPhone: data.ownerPhone,
            title: data.title,
            content: data.content,
            type: data.type,
            status: data.status || '待处理',
            submitTime: this.formatDateTime(data.submitTime),
            handleTime: this.formatDateTime(data.handleTime),
            finishTime: this.formatDateTime(data.finishTime),
            handlerName: data.handlerName || '',
            result: data.result || ''
          };
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取投诉信息失败:', error);
          ElMessage.error('获取投诉信息失败');
          this.loading = false;
        });
    },
    
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return null;
      const date = new Date(dateTimeStr);
      if (isNaN(date.getTime())) return null;
      
      return date.toISOString().slice(0, 19).replace('T', ' ');
    },
    
    submitForm() {
      this.$refs.complaintForm.validate(valid => {
        if (valid) {
          this.loading = true;
          
          // 构建提交数据
          const submitData = {
            id: this.formData.id,
            owner: {
              id: this.formData.ownerId
            },
            title: this.formData.title,
            content: this.formData.content,
            type: this.formData.type,
            status: this.formData.status,
            submitTime: this.formData.submitTime ? new Date(this.formData.submitTime).getTime() : null,
            handlerName: this.formData.handlerName,
            result: this.formData.result
          };
          
          // 根据状态设置相关时间
          if (submitData.status === '处理中') {
            submitData.handleTime = this.formData.handleTime ? 
              new Date(this.formData.handleTime).getTime() : 
              new Date().getTime();
          }
          
          if (submitData.status === '已完成') {
            submitData.finishTime = this.formData.finishTime ? 
              new Date(this.formData.finishTime).getTime() : 
              new Date().getTime();
          }
          
          if (this.isEdit) {
            // 更新投诉信息
            axios.put(`/api/complaints/${submitData.id}`, submitData)
              .then(() => {
                ElMessage.success('更新投诉信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('更新投诉信息失败:', error);
                ElMessage.error('更新投诉信息失败');
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            // 新增投诉信息
            axios.post('/api/complaints', submitData)
              .then(() => {
                ElMessage.success('新增投诉信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('新增投诉信息失败:', error);
                ElMessage.error('新增投诉信息失败');
              })
              .finally(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    
    goBack() {
      this.$router.push('/property/service/complaint');
    }
  }
};
</script>

<style scoped>
.complaint-add {
  padding: 20px;
}

.form-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-page-header {
  margin-bottom: 20px;
}
</style>
